
class MoonRecordInventory {
  /** @type {MoonRecord[]>} 记录[] */
  cache = [];

  constructor(obj) {
    /** @type {function} */
    this.assetPath = obj.assetPath;
  }

  /**
   * @param {boolean} refresh 是否强制刷新
   * @returns {Promise<MoonRecord[]>}
   */
  load(refresh = false) {
    if (!refresh && this.cache.length > 0) {
      return Promise.resolve(this.cache);
    }

    return fetch(this.assetPath('data/planetaryExploration/moon_record.json'))
			.then(res => (res.ok) ? res.json() : null)
			.then(data => {
        return this.cache = this.convert(data);
			});
  }

  /**
   * @param {{version : string, list : object[]}} data
   * @returns {MoonRecord[]}
   */
  convert(data) {
    console.log(`data version: ${data.version}`);
    return data.list.map( it => new MoonRecord().from(it) );
  }

}

class MoonRecord {
  year = 0;
  country = 'unknown';
  /** @type {string[]} */
  countries = null;
  /** @type {string[]} */
  payloads = null;
  /** @type {{ key : string, type? : string, result: number, payloads? :string[] }[]} */
  missions = null;
  props = {};

  from(raw) {
    this.year = raw.y;

    if (raw.c instanceof Array) {
      this.countries = raw.c;
    } else {
      this.countries = [raw.c];
    }
    this.country = this.countries[0];

    this.payloads = raw.p;
    if (raw.props) {
      Object.assign(this.props, raw.props);
    }

    this.missions = raw.missions.map(it => {
      let result = {};
      result.key = it.key;
      result.result = it.r == null ? 1 : it.r;

      if (it.type) {
        result.type = it.type;
      }
      if (it.payloads) {
        result.payloads = it.payloads;
      }
      return result;
    });

    return this;
  }

  /**
   * 既定任务是否成功. 有特殊说明的按特殊说明处理, 否则存在任务是圆满成功的返回 true
   */
  isSuccess() {
    if (this.props['result'] != null) {
      return this.props['result'] > 0;
    }

    if (!this.missions) {
      return false;
    }

    return this.missions.some(m => m.result == 1);
  }
}

export {
  MoonRecordInventory, MoonRecord
};
